layui.use(['util'], function (util) {

    var
        table = util.table,//table
        form = util.form,//table
        upload = util.upload,//table
        layedit = util.layedit, //html编辑器
        layer = util.layer;//layer


    var topics = {

        // 存放静态常量 富文本对象
        topicEditerObj: null,

        topicCateGorys: [],

        imgUrl: "",

        constants: {
            html: {
                edit: appUrl + "/resources/js/lib/topics/edit.html"
            },
            api: {
                edit: appUrl + "/topics/edit",
                uploadImage: appUrl + '/topics/uploadTopicsImage',
                del: appUrl + "/topics/del",
                add: appUrl + "/topics/add",
                querytopicCategory: appUrl + '/topicCategory/queryList',
                queryList: appUrl + '/topics/queryList'
            }
        },

        init: function () {
            this.builertopicCateGorys();
            this.renderPage();
        },

        builertopicCateGorys: function () {
            var self = this;
            util.send(this.constants.api.querytopicCategory, {}, {
                success: function (resp) {
                    self.topicCateGorys = resp.data || [];
                }
            })
        },
        renderPage: function () {
            var self = this;
            //执行一个 table 实例
            table.render({
                elem: '#topicsTable'
                , height: 600
                , url: self.constants.api.queryList//数据接口
                , method: 'post' //如果无需自定义HTTP类型，可不加该参数
                , title: '用户表'
                , page: true //开启分页
                , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                , totalRow: true //开启合计行
                , parseData: function (resp) {
                    var data = resp.data || [];

                    resp.data = data.map(function (value) {

                        value.addTimeStr = util.getTime(value.addTime);

                        return value;
                    });
                    return resp;

                } //开启合计行
                , cols: [[ //表头
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'title', title: '标题', width: '15%'}
                    , {field: 'subtitle', title: '副标题', width: '10%'}
                    , {
                        fixed: 'right',
                        title: '主图',
                        width: '10%',
                        templet: '<div><img src="{{d.itemPicUrl}}" height="100" width="100"/></div>'
                    }
                    , {
                        fixed: 'right',
                        title: '附图',
                        width: '10%',
                        templet: '<div><img src="{{d.scenePicUrl}}" height="100" width="100"/></div>'
                    }
                    , {fixed: 'right', title: '是否展示', width: '10%', align: 'center', templet: '#showStatus'}
                    , {fixed: 'right', title: '订单状态', width: '10%', align: 'center', templet: '#payStatus'}
                    , {field: 'addTimeStr', title: '下单时间', width: '10%'}
                    , {fixed: 'right', title: '操作', width: '10%', align: 'center', toolbar: '#topicsTableBar'}
                ]]
            });

            //监听头工具栏事件
            table.on('toolbar(topicsFilter)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id)
                    , data = checkStatus.data; //获取选中的数据
                switch (obj.event) {
                    case 'add':
                        self.add(obj.data || {});
                        break;
                    case 'update':
                        if (data.length === 0) {
                            layer.msg('请选择一行');
                        } else if (data.length > 1) {
                            layer.msg('只能同时编辑一个');
                        } else {
                            layer.alert('编辑 [id]：' + checkStatus.data[0].id);
                        }
                        break;
                    case 'delete':
                        if (data.length === 0) {
                            layer.msg('请选择一行');
                        } else {
                            layer.msg('删除');
                        }
                        break;
                }
            });

            //监听行工具事件
            table.on('tool(topicsFilter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    , layEvent = obj.event; //获得 lay-event 对应的值
                if (layEvent === 'detail') {
                    layer.msg('查看操作');
                } else if (layEvent === 'del') {
                    layer.confirm('真的删除行么', function (index) {
                        obj.del(); //删除对应行（tr）的DOM结构
                        layer.close(index);
                        self.del(data);
                    });
                } else if (layEvent === 'edit') {
                    self.edit(data);
                }
            });
        },
        edit: function (data) {
            var self = this;
            data.topicCateGorys = self.topicCateGorys;
            util.templateProxy(self.constants.html.edit, data,
                {
                    success: function (formData) {
                        layedit.set({//设置图片的传输地址
                            uploadImage: {
                                url: self.constants.api.uploadImage, //接口url
                                type: 'post' //默认postF
                            }
                        });
                        form.val("editTopicForm", data);
                        form.render();
                        self.topicEditerObj = layedit.build('topicDescription');
                        self.initUpload("#itemPicUrl");
                    },
                    title: '编辑类目',
                    area: ['800px', '600px'],
                    confirm: function (formData) {
                        formData.content = layedit.getContent(self.topicEditerObj);
                        formData.itemPicUrl = self.imgUrl;
                        formData.isShow = formData.isShow === 'on';
                        formData.topicTemplateId = 0;
                        formData.topicTagId = 0;
                        formData.sortOrder = 0;
                        util.post(self.constants.api.edit, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.closeAll();
                                self.renderPage();
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },
        add: function (data) {
            var self = this;
            data.topicCateGorys = self.topicCateGorys;
            util.templateProxy(self.constants.html.edit, data,
                {
                    success: function (formData) {
                        layedit.set({//设置图片的传输地址
                            uploadImage: {
                                url: self.constants.api.uploadImage, //接口url
                                type: 'post' //默认post
                            }
                        });
                        form.val("editTopicForm", data);
                        form.render();
                        self.topicEditerObj = layedit.build('topicDescription');
                        self.initUpload("#itemPicUrl");
                    },
                    title: '添加类目',
                    area: ['800px', '600px'],
                    confirm: function (formData) {
                        formData.content = layedit.getContent(self.topicEditerObj);
                        formData.itemPicUrl = self.imgUrl;
                        util.post(self.constants.api.add, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.msg(resp.msg);
                                layer.closeAll();
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },
        del: function (data) {
            util.post(this.constants.api.del, {id: data.id}, function (resp) {
                layer.closeAll();
            });
        },

        initUpload: function (uploadId) {
            var self = this;
            upload.render({
                elem: uploadId
                , url: self.constants.api.uploadImage
                , accept: 'file' //普通文件
                , size: 200 //限制文件大小，单位 200kB
                , exts: 'jpg|png|jpeg' //只允许上传压缩文件
                , done: function (res) {
                    if (res && res.data) {
                        self.imgUrl = res.data.src || "";
                    }
                }, choose: function (obj) {
                    obj.preview(function (index, file, result) {
                        $(uploadId).find('img').attr('src', result);
                    });
                }
            });
        }
    };

    topics.init();
});